package com.aliwo.aspect.annotation;

import com.aliwo.entity.MessageRecord;
import com.aliwo.mapper.MessageRecordMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 切面处理类.
 *
 * @author Xu Yayuan
 * @date 2021/11/18
 */
@Aspect
@Component
public class AspectConfig {

    private static final Logger logger = LoggerFactory.getLogger(AspectConfig.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MessageRecordMapper mapper;

    /**
     * 记录消息日志
     */
    @Around("@annotation(com.aliwo.aspect.annotation.MessageLog)")
    public Object aroundMessage(ProceedingJoinPoint point) throws Throwable {
        String json = objectMapper.writeValueAsString(point.getArgs());
        //执行方法
        Object object = point.proceed();
        // 执行方法后的操作
        MessageRecord messageRecord = new MessageRecord();
        MethodSignature signature = (MethodSignature) point.getSignature();
        MessageLog messageLog = signature.getMethod().getAnnotation(MessageLog.class);
        // 发送的内容
        messageRecord.setContent(json);
        // 类名
        messageRecord.setClassName(point.getTarget().getClass().getName());
        // 方法名
        messageRecord.setMethodName(signature.getName());
        //请求的参数
        Object[] args = point.getArgs();
        try{
            List<String> list = new ArrayList<>();
            for (Object o : args) {
                list.add(new Gson().toJson(o));
            }
            messageRecord.setParams(list.toString());
        }catch (Exception e){ }
        // 消息状态
        messageRecord.setStatus(Boolean.valueOf(object.toString()));
        // 消息类型
        messageRecord.setType(messageLog.value());
        messageRecord.setExeuTime(System.currentTimeMillis());
        // 记录注解上的描述信息
        messageRecord.setRemark(signature.getMethod().getAnnotation(MessageLog.class).value());
        Integer row = mapper.saveLog(messageRecord);
        if (1 == row) {
            logger.info("日志记录成功：{}", row);
        } else {
            logger.warn("日志记录失败：{}", row);
        }
        return object;
    }

}
